package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.entity.Video;
import com.yupi.springbootinit.service.VideoService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片服务实现类
 * @author gan
 * @date 2023/4/20 15:43
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Override
    public Page<Video> searchVideo(String searchText, long pageNum, long pageSize) {

        // current为偏移量
        long current = (pageNum - 1) * pageSize;
        String url = String.format("http://cn.bing.com/videos/search?q=%s&first=%s",searchText,current);
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据获取异常");
        }
        // 用css样式选择器找到元素,用class去找
        Elements elements = doc.select(".dg_u");
        List<Video> videoList = new ArrayList<>();
        int cur = 1;
        for (Element element : elements) {
            // 取出图片地址，在第一次用class找到的元素中用特定的属性去找
            Element a = element.select("a").get(0);
            Element image = element.select(".rms_iac").get(0);
            // 有些可能没有时间显示要特判
            Elements ts = element.select(".mc_bc_rc.items");
            Element time = ts.size() == 0 ? null : ts.get(0);
            String title = image.attr("data-alt");
            String imageUrl = image.attr("data-src");
            String videoUrl = a.attr("href");
            String videoDuration = time == null ? null : time.text();

            videoList.add(new Video(title,videoUrl,imageUrl,videoDuration));
            if (videoList.size() >= pageSize){
                break;
            }
        }
        Page<Video> videoPage = new Page<>(pageNum,pageSize);
        videoPage.setRecords(videoList);
        return videoPage;
    }
}
